"""
nacos服务使用

"""
import json
import random
import threading
import time
import requests
from components.nacos.connector import client, SERVICE_NAME, SERVICE_IP, SERVICE_PORT, NAMESPACE, VERSION


# 注册服务
def register_service():
    meta = {'version': VERSION}
    response = client.add_naming_instance(SERVICE_NAME, SERVICE_IP, SERVICE_PORT, NAMESPACE, metadata=meta)
    print('服务注册结果：', response)


# 每timeout秒发送一次心跳
def send_heartbeat_thread(timeout=5):
    def send_heartbeat():
        while True:
            response = client.send_heartbeat(SERVICE_NAME, SERVICE_IP, SERVICE_PORT, NAMESPACE)
            # print(response)
            time.sleep(timeout)

    heartbeat_thread = threading.Thread(target=send_heartbeat)
    heartbeat_thread.daemon = True
    heartbeat_thread.start()


# 获取服务基础url http://ip:port
def choose_url(hosts, service_name, version='v1.0'):
    # 防止循环引用
    from components.memcache.connector import cache
    balance = cache.get('Balance_' + service_name)
    if not balance:
        balance = []
        for service in hosts:
            # print(service)
            # 保证是健康的，可用的
            if service['healthy'] == True and service['enabled'] == True:
                service_version = service['metadata']['version'] if 'version' in service['metadata'] else 'v1.0'
                # 保证版本对应的(实现版本共存 / 灰度发布)
                if service_version == version:
                    balance.extend([f"http://{service['ip']}:{service['port']}"] * int(service['weight']))
    else:
        balance = json.loads(balance)
    # 使用random.randint()生成一个随机索引
    # 注意：random.randint()包括两端的值，所以range的上限是len(balance)
    random_index = random.randint(0, len(balance) - 1)
    # 获取随机索引对应的URL
    url = balance[random_index]
    # 从列表中删除该元素
    # 使用del语句直接通过索引删除元素
    del balance[random_index]
    if balance:
        cache.set('Balance_' + service_name, json.dumps(balance))
    else:
        cache.delete('Balance_' + service_name)
    return url


# 获取服务基础url http://ip:port
def get_service_url(service_name, version='v1.0'):
    try:
        from components.memcache.connector import cache
        cache.delete('Balance_' + service_name)
        data = client.list_naming_instance(service_name)
        if data and data['hosts']:
            if len(data['hosts']) < 2:
                service = data['hosts'][0]
                return f"http://{service['ip']}:{service['port']}"
                # 这里是本机调用测试
                # return f"http://localhost:{service['port']}"
            else:
                url = choose_url(data['hosts'], service_name, version)
                # print(url)
                return url
        else:
            return None
    except Exception as e:
        print(f"Error getting service URL: {e}")
    return None


# 调用其他服务代理
def proxy_service(service_name, path, request):
    version = request.headers.get('version') if request.headers.get('version') else 'v1.0'
    service_url = get_service_url(service_name, version)
    if not service_url:
        return {"code": 10016}
    if type(service_url) == dict:
        return {'code': 10000}
    url = f"{service_url}/{path}"
    response = requests.request(
        method=request.method,
        url=url,
        headers={key: value for key,
        value in request.headers if key != 'Host'},
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False
    )
    return response


def pull_config(dataid, group="DEFAULT_GROUP"):
    config = client.get_config(dataid, group)
    config = json.loads(config)
    return config
